package com.limou.controller;

import com.limou.pojo.Order;
import com.limou.pojo.Product;
import com.limou.pojo.User;
import com.limou.service.OrderService;
import com.limou.service.ProductService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    /**
     * 查询所有订单，返回值无订单中的商品信息
     * @param model
     * @return
     */
    @RequestMapping("/queryAllOrder")
    public String queryAllOrder(Model model) {
        List<Order> list = orderService.selectAll ();
        model.addAttribute ("orders",list);
        return "orderAll";
    }

    /**
     * 查询一个订单，返回的对象中有包含商品信息的集合
     * @param model
     * @param order 接收页面传过来的订单ID
     * @return
     */
    @RequestMapping("/queryByIdOrder")
    public String queryByIdOrder(Model model,Order order) {
        //System.out.println (order.getID ());
        order = orderService.selectOne (order);

        model.addAttribute ("order",order);

        return "orderInformation";
    }

    /**
     * 修改订单的状态，从结算改为已结算
     * @param model
     * @param order 接收页面传过来的订单ID
     * @return 修改后调用查询一个订单方法，从而跳转到单个订单详细信息页面 orderInformation.jsp
     */
    @RequestMapping("/updateOrderStatus")
    public String updateOrderStatus(Model model,Order order) {
        //System.out.println (order.getID ());
        orderService.updateOrder0 (order);
        return queryByIdOrder (model,order);
    }

    /**
     * 查询不同状态的订单
     * @param model
     * @param order
     * @return
     */
    @RequestMapping("/queryStatusOrder")
    public String queryStatusOrder(Model model,Order order) {
        //System.out.println (order.getStatus ());
        List<Order> list = orderService.selectOfStatusAll (order);
        model.addAttribute ("orders",list);
        return "orderAll";
    }

    /**
     * 添加一个新订单
     * @param model
     * @return
     */
    @RequestMapping("/addNewOrder")
    public String addNewOrder(Model model) {

        List<User> users = orderService.selectAllUser();

        List<Product> products = productService.list ();

        model.addAttribute ("users",users);
        model.addAttribute ("products",products);

        return "addNewOrder";
    }

    /**
     * 添加一个新订单
     * @param ids 包含商品id的数组
     * @param uid 用户id
     * @param request 请求对象
     * @return
     */
    @PostMapping(value ="/addOrder",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String addOrder(int[] ids, int uid, HttpServletRequest request) {
        System.out.println ("addOrder------------");
        if (uid == 0) {
            return "无效订单，未选择用户";
        }
        List<Product> products = new ArrayList<> ();
        for (int i: ids) {
            Product product = productService.queryProductById (i);
            //System.out.println (product);
            String number = request.getParameter ("numbers"+i);
            int numb = Integer.parseInt (number);
            product.setStock (numb);
            products.add (product);
            //System.out.println (numb);
        }
        //System.out.println ("--------------------------------");
        //计算该订单总金额
        double moneys = orderService.totalMoney (products);
        //减去库存
        orderService.updateProductStack(products);
        Order order = new Order ();
        order.setUid (uid);
        order.setTotalMoney (moneys);
        orderService.insertOrder (order);
        int orderID = orderService.selectNewId ();
        orderService.insertOrderProduct (orderID,products);
        //System.out.println ("--------------------------------");

        return "添加成功";
    }

    //导出excel表
    @RequestMapping("/saveExcel")
    @ResponseBody
//    输出为表格
    public ResponseEntity<byte[]> saveExcel(Order order) throws IOException {
        //获取订单信息
        order = orderService.selectOne (order);

        String fileName="order.xls";// 设置文件名
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();//创建实例
        HSSFSheet sheet = hssfWorkbook.createSheet();//创建第一页sheet表
        Row row = sheet.createRow(0);//创建第一行
        row.createCell(0).setCellValue("订单编号");//给第一行第一列设置标题
        row.createCell(1).setCellValue("用户昵称");//给第一行第二列设置标题
        row.createCell(2).setCellValue("用户名");//给第一行第二列设置标题
        row.createCell(3).setCellValue("总金额");//给第一行第三列设置标题
        row.createCell(4).setCellValue("订单状态");//给第一行第四列设置标题

        //添加订单基本信息
        row = sheet.createRow(sheet.getLastRowNum()+1);//获取刚刚创建的最后一行的行数
        row.createCell(0).setCellValue(order.getID ());
        row.createCell(1).setCellValue(order.getUser ().getName ());
        row.createCell(2).setCellValue(order.getUser ().getUsername ());
        row.createCell(3).setCellValue(order.getTotalMoney ());
        String statusOrder="";
        if (order.getStatus () == 1) {
            statusOrder = "未结算";
        }
        if (order.getStatus () == 0) {
            statusOrder = "已结算";
        }
        row.createCell(4).setCellValue(statusOrder);

        //添加一个空白行
        row = sheet.createRow(sheet.getLastRowNum()+1);//获取刚刚创建的最后一行的行数
        //添加订单商品信息
        row = sheet.createRow(sheet.getLastRowNum()+1);//获取刚刚创建的最后一行的行数
        row.createCell(0).setCellValue("商品编号");
        row.createCell(1).setCellValue("商品名称");
        row.createCell(2).setCellValue("商品价格");
        row.createCell(3).setCellValue("商品描述");
        row.createCell(4).setCellValue("商品数量");
        //动态把数据加入到刚刚创建的这个表
        //动态加入商品信息
        for (Product product : order.getGoodsList ()) {
            row = sheet.createRow(sheet.getLastRowNum()+1);//获取刚刚创建的最后一行的行数
            row.createCell(0).setCellValue(product.getId ());
            row.createCell(1).setCellValue(product.getName ());
            row.createCell(2).setCellValue(product.getPrice ());
            row.createCell(3).setCellValue(product.getDescription ());
            row.createCell(4).setCellValue(product.getStock ());
        }


        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        hssfWorkbook.write(byteArrayOutputStream);
        byte[] bytes=byteArrayOutputStream.toByteArray();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment",fileName);
        return new ResponseEntity<>(bytes,httpHeaders, HttpStatus.OK);
    }

}
